<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form
      :model="queryParams"
      inline
      size="small"
      v-show="showSearch"
      label-width="80px"
    >
      <!-- 第一行：姓名、证件编号、手机号码、单位名称 -->
      <el-form-item label="姓名">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 180px"
        />
      </el-form-item>

      <el-form-item label="证件编号">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入证件编号"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 180px"
        />
      </el-form-item>

      <el-form-item label="手机号码">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 180px"
        />
      </el-form-item>

      <el-form-item label="单位名称">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入单位名称"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 180px"
        />
      </el-form-item>

      <!-- 第二行：报名时间、报名来源、证书编号、复审状态 -->
      <el-form-item label="报名时间">
        <el-date-picker
          v-model="queryParams.registrationTimeRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
          style="width: 180px"
        />
      </el-form-item>

      <el-form-item label="报名来源">
        <el-select
          v-model="queryParams.registrationSource"
          placeholder="请选择报名来源"
          clearable
          style="width: 180px"
        >
          <el-option label="线上" value="online" />
          <el-option label="线下" value="offline" />
        </el-select>
      </el-form-item>

      <el-form-item label="证书编号">
        <el-input
          v-model="queryParams.certificateNo"
          placeholder="请输入证书编号"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 180px"
        />
      </el-form-item>

      <el-form-item label="复审状态">
        <el-select
          v-model="queryParams.reviewStatus"
          placeholder="请选择复审状态"
          clearable
          style="width: 180px"
        >
          <el-option label="待审核" value="pending" />
          <el-option label="已通过" value="approved" />
          <el-option label="未通过" value="rejected" />
        </el-select>
      </el-form-item>

      <!-- 第三行：作业项目、缴费状态、档案状态、提交状态 -->
      <el-form-item label="作业项目">
        <el-select
          v-model="queryParams.workProject"
          placeholder="选择作业项目"
          clearable
          style="width: 180px"
        >
          <el-option label="电工" value="electrician" />
          <el-option label="焊工" value="welder" />
          <el-option label="起重" value="crane" />
        </el-select>
      </el-form-item>

      <el-form-item label="缴费状态">
        <el-select
          v-model="queryParams.paymentStatus"
          placeholder="选择缴费状态"
          clearable
          style="width: 180px"
        >
          <el-option label="已缴费" value="paid" />
          <el-option label="未缴费" value="unpaid" />
        </el-select>
      </el-form-item>

      <el-form-item label="档案状态">
        <el-select
          v-model="queryParams.fileStatus"
          placeholder="选择档案状态"
          clearable
          style="width: 180px"
        >
          <el-option label="已归档" value="archived" />
          <el-option label="未归档" value="unarchived" />
        </el-select>
      </el-form-item>

      <el-form-item label="提交状态">
        <el-select
          v-model="queryParams.submitStatus"
          placeholder="选择提交状态"
          clearable
          style="width: 180px"
        >
          <el-option label="已提交" value="submitted" />
          <el-option label="未提交" value="not_submitted" />
        </el-select>
      </el-form-item>

      <!-- 第四行：有效期起、有效期止 + 操作按钮 -->
      <el-form-item label="有效期起">
        <el-date-picker
          v-model="queryParams.validStart"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
          style="width: 180px"
        />
      </el-form-item>

      <el-form-item label="有效期止">
        <el-date-picker
          v-model="queryParams.validEnd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
          style="width: 180px"
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 第一行：报名列表、新增报名、发票、已预开票 -->
      <el-col :span="4">
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
          "
        >
          <!-- 左侧按钮 -->
          <div style="display: flex">
            <span class="group-label">报名列表</span>
            <el-button size="medium" @click="handleExport">导出</el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div style="display: flex; padding: 10px 0; float: left">
          <span class="group-label">新增报名</span>
          <el-button size="medium" @click="handleAddPersonalReview"
            >新增个人复审</el-button
          >
          <el-button size="medium" @click="handleAddGroupReexamination"
            >新增集体复审</el-button
          >
          <el-button size="medium" @click="handleImportReexamination"
            >导入信息复审</el-button
          >
        </div>
      </el-col>
      <el-col :span="8">
        <div style="display: flex; padding: 10px 0; float: left">
          <span class="group-label">发票</span>
          <el-button size="medium" @click="1">查看发票</el-button>
          <el-button size="medium" @click="1">已预开票</el-button>
        </div>
      </el-col>
      <el-col :span="4">
        <div style="display: flex; float: right">
          <column-config-dialog-vue
            :showSearch.sync="showSearch"
            :columns="tableColumns"
            @queryTable="getList"
          ></column-config-dialog-vue>
        </div>
      </el-col>

      <!-- 第二行：报名信息 -->
      <el-col :span="24">
        <div
          style="display: flex; flex-wrap: wrap; gap: 10px; padding-top: 10px"
        >
          <!-- 报名信息 -->
          <div style="display: flex; align-items: center">
            <span class="group-label">报名信息</span>
            <el-button size="small" @click="handleView">查看详情</el-button>
            <el-button size="small" @click="handleEdit">修改</el-button>
            <el-button size="small" @click="handleDelete">删除</el-button>
            <el-button size="small" @click="handleRemark">备注</el-button>
            <el-button size="small" @click="handlePrintApplication"
              >打印申请表</el-button
            >
            <el-button size="small" @click="handleSubmitApplication"
              >提交申请表</el-button
            >
            <el-button size="small" @click="1">取消提交申请表</el-button>
          </div>
        </div>
      </el-col>

      <!-- 第三行：档案、退款 -->
      <el-col :span="24">
        <div
          style="display: flex; flex-wrap: wrap; gap: 10px; padding-top: 10px"
        >
          <!-- 档案 -->
          <div style="display: flex; align-items: center">
            <span class="group-label">档案</span>
            <el-button size="small" @click="handleExportTest1" :disabled="ids.length === 0">档案扫描</el-button>
            <el-button size="small" @click="handleExportTest2"  :disabled="ids.length === 0">档案上传</el-button>
            <el-button size="small" @click="handleExportTest2"  :disabled="ids.length === 0">档案查看</el-button>
            <el-button size="small" @click="handleExportTest2"  :disabled="ids.length === 0">线上档案确认</el-button>
          </div>

          <!-- 退款 -->
          <div style="display: flex; align-items: center">
            <span class="group-label">退款</span>
            <el-button size="small" @click="handleStartRefund"
              >发起退款</el-button
            >
            <el-button size="small" @click="handleCancelRefund"
              >取消退款</el-button
            >
          </div>
        </div>
      </el-col>

      <!-- 第四行：缴费、证书信息 -->
      <el-col :span="24">
        <div
          style="display: flex; flex-wrap: wrap; gap: 10px; padding-top: 10px"
        >
          <!-- 缴费 -->
          <div style="display: flex; align-items: center">
            <span class="group-label">缴费</span>
            <el-button size="small" @click="1">缴费二维码</el-button>
            <el-button size="small" @click="handlePaymentMethodChange(2)"
              >转账缴费</el-button
            >
            <el-button size="small" @click="handlePaymentMethodChange(3)"
              >现金缴费</el-button
            >
            <el-button size="small" @click="handlePaymentMethodChange(4)"
              >POS机缴费</el-button
            >
          </div>

          <!-- 证书信息 -->
          <div style="display: flex; align-items: center">
            <span class="group-label">证书信息</span>
            <el-button size="small" @click="handleCertificateInfo"
              >证书信息</el-button
            >
            <el-button size="small" @click="handleSyncCertificate"
              >同步证书信息</el-button
            >
            <el-button size="small" @click="handleImportCertificate"
              >导入证书信息</el-button
            >
            <el-button size="small" @click="handleStudentNotice"  :disabled="ids.length ===0"
              >学员通知</el-button
            >
            <el-button size="small" @click="handleReviewRegistration"
              >已提交考试系统</el-button
            >
          </div>
        </div>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="specialCertificateList"
      @selection-change="handleSelectionChange"
    >
      <!-- 选中列 -->
      <el-table-column type="selection" width="55" align="center" />

      <!-- 证书类型 -->
      <el-table-column
        label="证书类型"
        align="center"
        prop="certificateType"
        width="100"
        v-if="
          tableColumns.find((col) => col.prop === 'certificateType').visible
        "
      >
        <template slot-scope="scope">
          <span>{{
            dictCache.certificate_type[scope.row.certificateType]
          }}</span>
        </template>
      </el-table-column>

      <!-- 姓名 -->
      <el-table-column
        label="姓名"
        align="center"
        prop="studentName"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'studentName').visible"
      />

      <!-- 证件编号 -->
      <el-table-column
        label="证件编号"
        align="center"
        prop="idNumber"
        width="150"
        v-if="tableColumns.find((col) => col.prop === 'idNumber').visible"
      />

      <!-- 性别 -->
      <el-table-column
        label="性别"
        align="center"
        prop="sex"
        width="80"
        v-if="tableColumns.find((col) => col.prop === 'sex').visible"
      />

      <!-- 电话 -->
      <el-table-column
        label="电话"
        align="center"
        prop="phonenumber"
        width="120"
        v-if="tableColumns.find((col) => col.prop === 'phonenumber').visible"
      />

      <!-- 单位名称 -->
      <el-table-column
        label="单位名称"
        align="center"
        prop="unitName"
        width="120"
        v-if="tableColumns.find((col) => col.prop === 'unitName').visible"
      />

      <!-- 报名来源 -->
      <el-table-column
        label="报名来源"
        align="center"
        prop="registrationMethod"
        width="100"
        v-if="
          tableColumns.find((col) => col.prop === 'registrationMethod').visible
        "
      >
        <template slot-scope="scope">
          <span>{{
            dictCache.registration_method[scope.row.registrationMethod]
          }}</span>
        </template>
      </el-table-column>

      <!-- 联系人 -->
      <el-table-column
        label="联系人"
        align="center"
        prop="contact"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'contact').visible"
      />

      <!-- 联系人电话 -->
      <el-table-column
        label="联系人电话"
        align="center"
        prop="unitPhonenumber"
        width="120"
        v-if="
          tableColumns.find((col) => col.prop === 'unitPhonenumber').visible
        "
      />

      <!-- 作业种类 -->
      <el-table-column
        label="作业种类"
        align="center"
        prop="workCategory"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'workCategory').visible"
      />

      <!-- 作业项目 -->
      <el-table-column
        label="作业项目"
        align="center"
        prop="workProject"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'workProject').visible"
      />

      <!-- 原发证机关 -->
      <el-table-column
        label="原发证机关"
        align="center"
        prop="originalAuthority"
        width="120"
        v-if="
          tableColumns.find((col) => col.prop === 'originalAuthority').visible
        "
      />

      <!-- 原证书编号 -->
      <el-table-column
        label="原证书编号"
        align="center"
        prop="originalCertificateNo"
        width="150"
        v-if="
          tableColumns.find((col) => col.prop === 'originalCertificateNo')
            .visible
        "
      />

      <!-- 首次领证日期 -->
      <el-table-column
        label="首次领证日期"
        align="center"
        prop="firstIssueDate"
        width="120"
        v-if="tableColumns.find((col) => col.prop === 'firstIssueDate').visible"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.firstIssueDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <!-- 到期日期 -->
      <el-table-column
        label="到期日期"
        align="center"
        prop="expireDate"
        width="120"
        v-if="tableColumns.find((col) => col.prop === 'expireDate').visible"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <!-- 费用 -->
      <el-table-column
        label="费用"
        align="center"
        prop="specialCertificateFee"
        width="80"
        v-if="
          tableColumns.find((col) => col.prop === 'specialCertificateFee')
            .visible
        "
      />

      <!-- 缴费状态 -->
      <el-table-column
        label="缴费状态"
        align="center"
        prop="paymentState"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'paymentState').visible"
      >
        <template slot-scope="scope">
          <span>{{ dictCache.payment_status[scope.row.paymentState] }}</span>
        </template>
      </el-table-column>

      <!-- 发票状态 -->
      <el-table-column
        label="发票状态"
        align="center"
        prop="invoiceStatus"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'invoiceStatus').visible"
      >
        <template slot-scope="scope">
          <span>{{ dictCache.invoice_status[scope.row.invoiceStatus] }}</span>
        </template>
      </el-table-column>

      <!-- 档案状态 -->
      <el-table-column
        label="档案状态"
        align="center"
        prop="recordStatus"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'recordStatus').visible"
      >
        <template slot-scope="scope">
          <span>{{ dictCache.record_status[scope.row.recordStatus] }}</span>
        </template>
      </el-table-column>

      <!-- 档案缺失情况 -->
      <el-table-column
        label="档案缺失情况"
        align="center"
        prop="recordMissing"
        width="120"
        v-if="tableColumns.find((col) => col.prop === 'recordMissing').visible"
      />

      <!-- 是否上传考试系统 -->
      <el-table-column
        label="是否上传考试系统"
        align="center"
        prop="uploadExamSystem"
        width="150"
        v-if="
          tableColumns.find((col) => col.prop === 'uploadExamSystem').visible
        "
      >
        <template slot-scope="scope">
          <span>{{
            dictCache.upload_exam_system[scope.row.uploadExamSystem]
          }}</span>
        </template>
      </el-table-column>

      <!-- 证书编号 -->
      <el-table-column
        label="证书编号"
        align="center"
        prop="certificateNo"
        width="150"
        v-if="tableColumns.find((col) => col.prop === 'certificateNo').visible"
      />

      <!-- 证书有效期起 -->
      <el-table-column
        label="证书有效期起"
        align="center"
        prop="validityStartTime"
        width="120"
        v-if="
          tableColumns.find((col) => col.prop === 'validityStartTime').visible
        "
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.validityStartTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>

      <!-- 证书有效期止 -->
      <el-table-column
        label="证书有效期止"
        align="center"
        prop="validityEndTime"
        width="120"
        v-if="
          tableColumns.find((col) => col.prop === 'validityEndTime').visible
        "
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.validityEndTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <!-- 发证单位 -->
      <el-table-column
        label="发证单位"
        align="center"
        prop="issuingAuthority"
        width="120"
        v-if="
          tableColumns.find((col) => col.prop === 'issuingAuthority').visible
        "
      />

      <!-- 备注 -->
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        width="120"
        v-if="tableColumns.find((col) => col.prop === 'remark').visible"
      />

      <!-- 操作 -->
      <el-table-column
        label="操作"
        align="center"
        width="240"
        class-name="small-padding fixed-width"
        v-if="tableColumns.find((col) => col.prop === 'operation').visible"
      >
        <template slot-scope="scope">
          <!-- 查看按钮 -->
          <el-button size="mini" type="text" @click="handleRowView(scope.row)"
            >查看</el-button
          >

          <!-- 修改按钮 -->
          <!-- <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            >修改</el-button
          > -->
          <el-button size="mini" type="text" @click="handleEditRow(scope.row)"
            >修改</el-button
          >

          <!-- 打印申请表按钮 -->
          <el-button
            size="mini"
            type="text"
            @click="handlePrintApplication(scope.row)"
            >打印申请表</el-button
          >

          <!-- 提交申请表按钮 -->
          <el-button
            size="mini"
            type="text"
            @click="handleSubmitApplication(scope.row)"
            >提交申请表</el-button
          >

          <!-- 缴费方式按钮 -->
          <!-- <el-button
            size="mini"
            type="text"
            @click="handlePaymentMethod(scope.row)"
            >缴费方式</el-button
          > -->

          <!-- 删除按钮 -->
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改特设证书管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="证书模板id" prop="templateId">
          <el-input v-model="form.templateId" placeholder="请输入证书模板id" />
        </el-form-item>
        <el-form-item label="学员id" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学员id" />
        </el-form-item>
        <el-form-item label="项目id" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目id" />
        </el-form-item>
        <el-form-item label="报名id" prop="registrationId">
          <el-input v-model="form.registrationId" placeholder="请输入报名id" />
        </el-form-item>
        <el-form-item label="作业种类" prop="workCategory">
          <el-input v-model="form.workCategory" placeholder="请输入作业种类" />
        </el-form-item>
        <el-form-item label="作业项目" prop="workProject">
          <el-input v-model="form.workProject" placeholder="请输入作业项目" />
        </el-form-item>
        <el-form-item label="证书编号" prop="certificateNo">
          <el-input v-model="form.certificateNo" placeholder="请输入证书编号" />
        </el-form-item>
        <el-form-item label="证书有效期起" prop="validityStartTime">
          <el-date-picker
            clearable
            v-model="form.validityStartTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择证书有效期起"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="证书有效期止" prop="validityEndTime">
          <el-date-picker
            clearable
            v-model="form.validityEndTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择证书有效期止"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发证单位" prop="issuingAuthority">
          <el-input
            v-model="form.issuingAuthority"
            placeholder="请输入发证单位"
          />
        </el-form-item>
        <el-form-item label="原发证机关" prop="originalAuthority">
          <el-input
            v-model="form.originalAuthority"
            placeholder="请输入原发证机关"
          />
        </el-form-item>
        <el-form-item label="原证书编号" prop="originalCertificateNo">
          <el-input
            v-model="form.originalCertificateNo"
            placeholder="请输入原证书编号"
          />
        </el-form-item>
        <el-form-item label="首次领证日期" prop="firstIssueDate">
          <el-date-picker
            clearable
            v-model="form.firstIssueDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择首次领证日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期日期" prop="expireDate">
          <el-date-picker
            clearable
            v-model="form.expireDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择到期日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="费用" prop="specialCertificateFee">
          <el-input
            v-model="form.specialCertificateFee"
            placeholder="请输入费用"
          />
        </el-form-item>
        <el-form-item label="缴费id" prop="paymentId">
          <el-input v-model="form.paymentId" placeholder="请输入缴费id" />
        </el-form-item>
        <el-form-item label="发票id" prop="invoiceId">
          <el-input v-model="form.invoiceId" placeholder="请输入发票id" />
        </el-form-item>
        <el-form-item
          label="是否上传考试系统(0:否,1:是)"
          prop="uploadExamSystem"
        >
          <el-input
            v-model="form.uploadExamSystem"
            placeholder="请输入是否上传考试系统(0:否,1:是)"
          />
        </el-form-item>
        <el-form-item label="临近过期期限(天)" prop="expireReminderDays">
          <el-input
            v-model="form.expireReminderDays"
            placeholder="请输入临近过期期限(天)"
          />
        </el-form-item>
        <el-form-item label="备注" prop="specialCertificateRemark">
          <el-input
            v-model="form.specialCertificateRemark"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker
            clearable
            v-model="form.createdTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedTime">
          <el-date-picker
            clearable
            v-model="form.updatedTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增个人复审资料 -->
    <add-personal-review
      ref="addPersonalReview"
      :dict-data="dictData"
      @submit-complete="handleRefresh"
    ></add-personal-review>
    <!-- 新增集体复审 -->
    <add-group-reexamination
      ref="addGroupReexamination"
      :dict-data="dictData"
      @next="openGroupPersonList"
      @submit-complete="handleRefresh"
    ></add-group-reexamination>
    <group-person-list
      ref="groupPersonList"
      :dict-data="dictData"
    ></group-person-list>

    <!-- 证书信息 -->
    <CertificateInfoDialog
      :visible.sync="dialogVisible"
      :user-info="userInfo"
      @submit="handleCertificateSubmit"
    />
    <!-- 导入证书信息 -->
    <ImportCertificateDialog
      :visible.sync="importVisible"
      @import-success="handleImportSuccess"
    />
    <!-- 导入信息复审 -->
    <ImportReexaminationDialog
      :visible.sync="importReexaminationVisible"
      @import-success="handleImportReexaminationSuccess"
    />
    <!-- 发起退费 -->
    <InitiateRefundDialog
      :visible.sync="showRefundDialogInitiate"
      :apply-info="refundFormData"
      :dict="dictCache"
      @submit="handleRefundSubmitInitiate"
      @close="handleInitiateRefundClose"
    ></InitiateRefundDialog>
    <!-- 取消退费 -->
    <CancelRefundDialog
      :visible.sync="showRefundDialogCancel"
      :apply-info="refundApplyInfoCancel"
      :dict="dictCache"
      @submit="handleRefundSubmitCancel"
    ></CancelRefundDialog>
    <!-- 提交申请表组件 -->
    <SubmitApplicationForm
      :visible="submitDialogVisible"
      :dialog-title="submitDialogTitle"
      :initial-file="selectedApplicationFile"
      @success="handleSubmitSuccess"
      @close="submitDialogVisible = false"
    />

    <file-upload-modal
      :visible="showUploadModal"
      :students="students"
      :businessId="registrationIdsUpload"
      :defaultMode="defaultMode"
      @update:visible="val => showUploadModal = val"
      @confirm="handleUploadConfirm"
      @close="handleModalClose"
    />


    <!-- 2. 档案上传确认组件 -->
    <FileUploadConfirmation
      :visible.sync="showFileConfirmation"
      :userData="studentInitialData"
      :registrationId="registrationId"
      dialog-title="员工档案上传确认"
      dialog-width="85%"
      @single-confirm="handleFileSubmit"
      @confirm="handleFileSubmit"
      @midway-confirm="handleMidwaySave"
      @close="closeAllModals"
    />


    <!-- 3. 操作结果提示 -->
    <el-dialog
      :visible.sync="showResultDialog"
      :title="resultSuccess ? '操作成功' : '操作失败'"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="result-content">
        <i class="el-icon-check-circle success-icon" v-if="resultSuccess"></i>
        <i class="el-icon-error-circle error-icon" v-else></i>
        <p>{{ resultMessage }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showResultDialog = false">确定</el-button>
      </div>
    </el-dialog>
     <!-- 学员通知弹窗 -->
      <student-notice-dialog
        :visible.sync="noticeDialogVisible"
        :class-id="currentClassId"
        @notice-sent="handleNoticeSent"
      />
  </div>
</template>

<script>
import {
  listSpecialCertificate,
  getSpecialCertificate,
  delSpecialCertificate,
  addSpecialCertificate,
  updateSpecialCertificate,
  getSpecialList
} from "@/api/certificate/specialCertificate";
import { getDicts } from "@/api/system/dict/data";
import { changePay, updateRecord, getRefundInfo } from "@/api/payment/payment";
import { getRegistration, exportData } from "@/api/training/registration";

import ColumnConfigDialogVue from "../../../components/ColumnConfig/ColumnConfigDialog.vue";
// 新增个人复审资料
import AddPersonalReview from "@/components/Certificate/reexamination/AddPersonalReview.vue";
//新增集体复审
import AddGroupReexamination from "@/components/Certificate/reexamination/AddGroupReexamination.vue";
//新增集体复审--- 个人列表
import GroupPersonList from "@/components/Certificate/reexamination/GroupPersonList.vue";
//证书信息
import CertificateInfoDialog from "../../../components/Certificate/specialCertificate/CertificateInfoDialog.vue";
//导入证书信息
import ImportCertificateDialog from "../../../components/Certificate/specialCertificate/ImportCertificateDialog.vue";
// 导入信息复审
import ImportReexaminationDialog from "../../../components/Certificate/reexamination/ImportReexaminationDialog.vue";
// 发起退费
import InitiateRefundDialog from "@/components/Payment/InitiateRefundDialog.vue";
// 取消退费
import CancelRefundDialog from "@/components/Payment/CancelRefundDialog.vue";
// 提交申请表
import SubmitApplicationForm from "@/components/Certificate/reexamination/SubmitApplicationForm.vue";

import FileUploadModal from "@/components/FileUpload/FileUploadModal.vue";
import FileUploadConfirmation from '@/components/FileUpload/FileUploadConfirmation.vue';
import {handleRecordsSubmit,selectRecordsByRegistrationIds} from "@/api/training/records";
import studentNoticeDialog from "@/components/class/studentNoticeDialog.vue";


export default {
  name: "SpecialCertificate",
  dicts: [
    "certificate_type",
    "review_status",
    "registration_method",
    "payment_status",
    "invoice_status",
    "record_status",
    "upload_exam_system",
    "payment_method",
    "training_type"
  ],
  components: {
    ColumnConfigDialogVue,
    AddPersonalReview,
    AddGroupReexamination,
    GroupPersonList,
    CertificateInfoDialog,
    ImportCertificateDialog,
    ImportReexaminationDialog,
    InitiateRefundDialog,
    CancelRefundDialog,
    SubmitApplicationForm,
    FileUploadModal,
    FileUploadConfirmation,
    studentNoticeDialog
  },
  data() {
    return {
      recordDto:null,
      currentClassId: '',
      noticeDialogVisible: false,

      registrationId:"",
      registrationIds:[],
      //档案数量
      recordDto:null,
      fileLimit:6,
      // 模态框控制
      showUploadModal: false,
      showFileConfirmation: false,
      showResultDialog: false,


      // 结果信息
      resultSuccess: false,
      resultMessage: '',
      submitResult: null,


      // 上传配置
      defaultMode: "0", // 覆盖模式 (cover 0 / append 1)
      registrationIdsUpload: "", // 报名id

      // 学员列表数据
      students: null,


      // 学员初始档案数据（模拟从后端获取）
      studentInitialData: [{
              id:0,
              name:"",
              registrationId:"",
              urls: [],
              remark:"",
              fileTypes:[]
              }],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 特设证书管理表格数据
      specialCertificateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certificateType: null,
        workCategory: null,
        workProject: null,
        certificateNo: null,
        validityStartTime: null,
        validityEndTime: null,
        issuingAuthority: null,
        reviewStatus: null,
        originalAuthority: null,
        originalCertificateNo: null,
        firstIssueDate: null,
        expireDate: null,
        specialCertificateFee: null,
        paymentId: null,
        invoiceId: null,
        uploadExamSystem: null,
        expireReminderDays: null,
        specialCertificateRemark: null,
        createdTime: null,
        updatedTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 缓存字典数据
      dictCache: {
        certificate_type: {},
        review_status: {},
        registration_method: {},
        payment_status: {},
        invoice_status: {},
        record_status: {},
        upload_exam_system: {},
        payment_method: {},
        training_type: {}
      },
      // 添加字典数据存储
      dictData: {
        unitNatureOptions: [],
        documentTypeOptions: [],
        nationOptions: [],
        educationOptions: [],
        administrativeAreaOptions: [],
        userTypeOptions: []
      },
      // 列显隐
      tableColumns: [
        { prop: "certificateType", label: "证书类型", visible: true },
        { prop: "studentName", label: "姓名", visible: true },
        { prop: "idNumber", label: "证件编号", visible: true },
        { prop: "sex", label: "性别", visible: true },
        { prop: "phonenumber", label: "电话", visible: true },
        { prop: "unitName", label: "单位名称", visible: true },
        { prop: "registrationMethod", label: "报名来源", visible: true },
        { prop: "contact", label: "联系人", visible: true },
        { prop: "unitPhonenumber", label: "联系人电话", visible: true },
        { prop: "workCategory", label: "作业种类", visible: true },
        { prop: "workProject", label: "作业项目", visible: true },
        { prop: "originalAuthority", label: "原发证机关", visible: true },
        { prop: "originalCertificateNo", label: "原证书编号", visible: true },
        { prop: "firstIssueDate", label: "首次领证日期", visible: true },
        { prop: "expireDate", label: "到期日期", visible: true },
        { prop: "specialCertificateFee", label: "费用", visible: true },
        { prop: "paymentState", label: "缴费状态", visible: true },
        { prop: "invoiceStatus", label: "发票状态", visible: true },
        { prop: "recordStatus", label: "档案状态", visible: true },
        { prop: "recordMissing", label: "档案缺失情况", visible: true },
        { prop: "uploadExamSystem", label: "是否上传考试系统", visible: true },
        { prop: "certificateNo", label: "证书编号", visible: true },
        { prop: "validityStartTime", label: "证书有效期起", visible: true },
        { prop: "validityEndTime", label: "证书有效期止", visible: true },
        { prop: "issuingAuthority", label: "发证单位", visible: true },
        { prop: "remark", label: "备注", visible: true },
        { prop: "operation", label: "操作", visible: true }
      ],
      // 新增个人复审资料

      //证书信息
      dialogVisible: false,
      userInfo: {
        studentName: " ",
        phonenumber: " ",
        unitName: " ",
        sex: " ",
        address: " ",
        education: " ",
        postcode: " ",
        idNumber: " ",
        unitPhonenumber: " ",
        workCategory: " ",
        workProject: " "
      },
      //导入证书信息
      importVisible: false,
      //导入信息复审
      importReexaminationVisible: false,
      // 退费发起
      showRefundDialogInitiate: false,
      refundFormData: {},
      // 退费取消
      showRefundDialogCancel: false,
      refundApplyInfoCancel: {},
      //缴费ids
      tempPaymentRecordIds: [],
      //报名ids--打印
      tempRegistrationIds: [],
      //提交申请表
      submitDialogVisible: false,
      submitDialogTitle: "提交申请表",
      selectedApplicationFile: null
    };
  },
  created() {
    this.getList();
    this.loadDicts();
    this.loadAllDicts(); // 加载所有需要用到的字典数据
  },
  methods: {
    async loadDicts() {
      this.dictCache.certificate_type = this.dict.label.certificate_type;
      this.dictCache.review_status = this.dict.label.review_status;
      this.dictCache.registration_method = this.dict.label.registration_method;
      this.dictCache.payment_status = this.dict.label.payment_status;
      this.dictCache.invoice_status = this.dict.label.invoice_status;
      this.dictCache.record_status = this.dict.label.record_status;
      this.dictCache.upload_exam_system = this.dict.label.upload_exam_system;
      this.dictCache.payment_method = this.dict.label.payment_method;
      this.dictCache.training_type = this.dict.label.training_type;
    },
    // 统一加载所有字典数据
    loadAllDicts() {
      const dictPromises = [
        getDicts("unit_nature"),
        getDicts("pxzx_zjlx"),
        getDicts("pub_mz"),
        getDicts("pxzx_xl"),
        getDicts("administrative_area"),
        getDicts("rylx")
      ];

      Promise.all(dictPromises)
        .then(responses => {
          this.dictData.unitNatureOptions = responses[0].data;
          this.dictData.documentTypeOptions = responses[1].data;
          this.dictData.nationOptions = responses[2].data;
          this.dictData.educationOptions = responses[3].data;
          this.dictData.administrativeAreaOptions = responses[4].data;
          this.dictData.userTypeOptions = responses[5].data;
        })
        .catch(error => {
          console.error("字典数据加载失败:", error);
        });
    },
    /** 查询特设证书管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.certificateType = "2";
      getSpecialList(this.queryParams).then(response => {
        this.specialCertificateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        specialCertificateId: null,
        certificateType: null,
        templateId: null,
        studentId: null,
        projectId: null,
        registrationId: null,
        workCategory: null,
        workProject: null,
        certificateNo: null,
        validityStartTime: null,
        validityEndTime: null,
        issuingAuthority: null,
        reviewStatus: null,
        originalAuthority: null,
        originalCertificateNo: null,
        firstIssueDate: null,
        expireDate: null,
        specialCertificateFee: null,
        paymentId: null,
        invoiceId: null,
        uploadExamSystem: null,
        expireReminderDays: null,
        specialCertificateRemark: null,
        createdTime: null,
        updatedTime: null,
        exampleOne: null,
        exampleTwo: null,
        exampleThree: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.validityStartTime) {
        this.queryParams.createStartTime = this.queryParams.validityStartTime[0];
        this.queryParams.createEndTime = this.queryParams.validityStartTime[1];
      }
      if (this.queryParams.validityEndTime) {
        this.queryParams.createStartTime = this.queryParams.validityEndTime[0];
        this.queryParams.createEndTime = this.queryParams.validityEndTime[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.recordDto=selection
      this.registrationIds = selection.map((item) => item.registrationId);

      this.ids = selection.map(item => item.specialCertificateId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.tempPaymentRecordIds = selection.map(item => item.paymentId);
      this.tempRegistrationIds = selection.map(item => item.registrationId);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加特设证书管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const specialCertificateId = row.specialCertificateId || this.ids;
      getSpecialCertificate(specialCertificateId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改特设证书管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.specialCertificateId != null) {
            updateSpecialCertificate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpecialCertificate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const specialCertificateIds = row.specialCertificateId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除特设证书管理编号为"' +
            specialCertificateIds +
            '"的数据项？'
        )
        .then(function() {
          return delSpecialCertificate(specialCertificateIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "training/specialCertificate/export",
        {
          ...this.queryParams
        },
        `specialCertificate_${new Date().getTime()}.xlsx`
      );
    },

    // 新增个人复审资料
    handleAddPersonalReview() {
      this.$refs.addPersonalReview.open("add");
    },
    // 新增集体复审方法
    handleAddGroupReexamination() {
      this.$refs.addGroupReexamination.open();
    },
    openGroupPersonList(unitInfo) {
      console.log("unitInfo:", unitInfo);
      this.$refs.groupPersonList.open(unitInfo); // 调用 GroupPersonList 的 open 方法
    },
    // 调用 getList 方法刷新页面数据
    handleRefresh() {
      this.$nextTick(() => {
        this.getList();
      });
    },
    // 导入信息复审
    handleImportReexamination() {
      this.importReexaminationVisible = true;
    },

    // 导入成功回调（可选）
    handleImportReexaminationSuccess(data) {
      this.$message.success("导入成功！");
      this.getList(); // 刷新列表
    },
    // 证书信息
    handleCertificateInfo() {
      // 检查是否有选中数据
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行操作");
        return;
      }

      // 从列表中找到选中的记录
      const selectedRow = this.specialCertificateList.find(
        item => item.specialCertificateId === this.ids[0]
      );

      if (selectedRow) {
        // 将选中行的数据映射到 userInfo 对象
        this.userInfo = {
          studentName: selectedRow.studentName || " ",
          phonenumber: selectedRow.phonenumber || " ",
          unitName: selectedRow.unitName || " ",
          sex: selectedRow.sex || " ",
          address: selectedRow.address || " ",
          education: selectedRow.education || " ",
          postcode: selectedRow.postalCode || " ",
          idNumber: selectedRow.idNumber || " ",
          unitPhonenumber: selectedRow.unitPhonenumber || " ",
          workCategory: selectedRow.workCategory || " ",
          workProject: selectedRow.workProject || " "
        };

        this.dialogVisible = true;
      } else {
        this.$message.warning("未找到选中的记录");
      }
    },
    handleCertificateSubmit(data) {
      console.log("提交的证书数据:", data);
      var params = {
        specialCertificateId: this.ids[0],
        originalCertificateNo: data.originalCertificateNo,
        issuingAuthority: data.issuingAuthority,
        validityStartTime: data.validityStartTime,
        validityEndTime: data.validityEndTime
      };
      updateSpecialCertificate(params)
        .then(response => {
          this.$modal.msgSuccess("更新成功");
          this.dialogVisible = false;
          this.getList(); // 刷新列表数据
        })
        .catch(error => {
          console.error("更新失败:", error);
          this.$modal.msgError("更新失败");
        });
    },
    handleSyncCertificate() {
      this.$message.info("点击了同步证书信息");
    },
    // 导入证书信息
    handleImportCertificate() {
      this.importVisible = true; // 显示导入对话框
    },
    // 处理导入成功事件
    handleImportSuccess(data) {
      this.$message.success("证书信息导入成功");
      this.getList(); // 刷新列表
    },
    handleStudentNotice(row) {
      let targetRow =null;
      // 优先获取行数据，无则取选中数据
      if(row.studentId !==undefined){
        targetRow =row
      }else{
        targetRow = this.recordDto[0];
        if (!targetRow ) return this.$message.warning('请选择一个学员');
      }
      this.currentClassId=targetRow.trainingClassId+""
      this.noticeDialogVisible =true
    },
    handleNoticeSent() {
      // 通知发送后处理
      this.noticeDialogVisible=false
      this.getList();
    },
    handleRemark() {
      this.$message.info("点击了备注");
    },
    handleReviewRegistration() {
      this.$message.info("点击了复审报名");
    },
    // 查看详情
    handleView() {
      const selectedRow = this.specialCertificateList.find(
        item => item.specialCertificateId === this.ids[0]
      );
      getRegistration(selectedRow.registrationId).then(response => {
        this.$refs.addPersonalReview.open("view", response.data);
      });
    },
    handleRowView(row) {
      this.$refs.addPersonalReview.open("view", row);
    },
    handleEdit() {
      // 检查是否选中了数据
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行修改");
        return;
      }

      // 从列表中找到选中的记录
      const selectedRow = this.specialCertificateList.find(
        item => item.specialCertificateId === this.ids[0]
      );

      if (selectedRow) {
        console.log("selectedRow:", selectedRow);
        getRegistration(selectedRow.registrationId).then(response => {
          this.$refs.addPersonalReview.open("edit", response.data);
        });
        // this.$refs.addPersonalReview.open("edit", selectedRow);
      }
    },
    handleEditRow(row) {
      if (row) {
        getRegistration(row.registrationId).then(response => {
          this.$refs.addPersonalReview.open("edit", response.data);
        });
        // this.$refs.addPersonalReview.open("edit", row);
      }
    },
    // 打印申请表
    handlePrintApplication(row) {
      let params = {};

      // 如果传入了 row 参数，只处理该行的 registrationId
      if (row && row.registrationId) {

        params = {
          registrationIds: [row.registrationId]
        };
        this.download(
          "/training/registration/export/applicationForm",
          JSON.stringify(params),
          `registration_${new Date().getTime()}.docx`,
          {
            transformRequest: [],
            headers: { "Content-Type": "application/json" }
          }
        );
        // exportData(params).then(response => {});
      } else {
        // 否则使用当前选中的 registrationIds（tempRegistrationIds）

        params = {
          registrationIds: this.tempRegistrationIds.map(id => String(id))
        };
        console.log("params:", params);
        this.download(
          "/training/registration/export/applicationForm",
          JSON.stringify(params),
          `registration_${new Date().getTime()}.zip`,
          {
            transformRequest: [],
            headers: { "Content-Type": "application/json" }
          }
        );
      }
    },

    // 提交申请表
    handleSubmitApplication(row) {
      // 设置选中的文件数据（如果有）
      if (row && row.applicationFile) {
        this.selectedApplicationFile = {
          name: row.applicationFileName,
          url: row.applicationFile,
          file: row.applicationFileBlob // 假设这是文件对象
        };
      } else {
        this.selectedApplicationFile = null;
      }

      this.submitDialogVisible = true;
    },
    // 处理提交成功回调
    handleSubmitSuccess(data) {
      this.$message.success("提交成功");
      this.getList(); // 刷新列表
    },
    // 缴费方式
    handlePaymentMethodChange(val) {
      const params = {
        paymentRecordIds: this.tempPaymentRecordIds,
        paymentMethod: val.toString()
      };
      changePay(params)
        .then(response => {
          this.$message.success("缴费方式更新成功");
          this.getList(); // 刷新列表
        })
        .catch(error => {
          this.$message.error("缴费方式更新失败：" + error.message);
        });
    },
    handlePaymentMethod(row) {
      this.$message.info("点击了缴费方式");
    },
    //发起退款
    handleRefundSubmitInitiate(submitData) {
      // 处理提交后关闭对话框
      const selectedRow = this.specialCertificateList.find(
        item => item.specialCertificateId === this.ids[0]
      );
      var params = {
        paymentRecordId: selectedRow.paymentId,
        refundAmount: submitData.auditForm.refundAmount,
        refundReason: submitData.auditForm.refundReason,
        paymentState: "6"
      };

      if (selectedRow) {
        updateRecord(params).then(res => {
          this.showRefundDialogInitiate = false;
          this.getList(); // 刷新列表
        });
      } else {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }
    },
    handleInitiateRefundClose() {
      this.showRefundDialogInitiate = false;
    },
    handleStartRefund() {
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }
      // 实现发起退费逻辑
      const selectedRow = this.specialCertificateList.find(
        item => item.specialCertificateId === this.ids[0]
      );
      if (selectedRow) {
        getRefundInfo(selectedRow.paymentId).then(res => {
          this.refundFormData = res.data;
        });
      } else {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }

      this.showRefundDialogInitiate = true;
    },
    handleCancelRefund() {
      // 实现取消退费逻辑
      const selectedRow = this.specialCertificateList.find(
        item => item.specialCertificateId === this.ids[0]
      );

      getRefundInfo(selectedRow.paymentId).then(res => {
        this.refundApplyInfoCancel = res.data;

        console.log("回显信息:", this.refundApplyInfoCancel);
      });

      this.showRefundDialogCancel = true;
    },
    // 取消退费申请---提交
    handleRefundSubmitCancel() {
      // 处理提交后关闭对话框
      const selectedRow = this.specialCertificateList.find(
        item => item.specialCertificateId === this.ids[0]
      );
      var params = {
        paymentRecordId: selectedRow.paymentId,
        paymentState: "1"
      };
      if (selectedRow) {
        updateRecord(params).then(() => {
          this.showRefundDialogCancel = false;
          this.getList(); // 刷新列表
        });
      } else {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }
    },
    /**
     * 处理FileUploadModal的确认事件
     * 上传完成后自动跳转到确认页面，并更新学员档案数据
     */
    getUrlsBySecondDir(query, fileList) {
    // 初始化结果数组
    const resultUrls = [];

    // 遍历文件列表
    fileList.forEach(file => {
        // 分割relativePath为目录数组（按"/"分割）
        const pathSegments = file.relativePath.split('/');
        // 校验路径格式（至少包含三级：一级/二级/文件名）
        if (pathSegments.length >= 3) {
            // 二级目录为数组的第1个索引（索引从0开始）
            const secondDir = pathSegments[1];
            // 精确匹配二级目录与查询字符串
            if (secondDir === query) {

                      // 匹配成功则添加url到结果数组
                      resultUrls.push(file.url);
                  }
              }
          })
          return resultUrls;
      },
    handleUploadConfirm(result) {
      console.log("文件上传完成，开始处理数据：", result);
      if(result.uploadMode === "1"){
          const targetStudents=result.targetStudents
          this.studentInitialData=targetStudents.map(item =>{
            let name =item.name
            let resultUrls =[]
            for(let i=0;i<this.students.length;i++){
              if(name === this.students[i].name){
                resultUrls = this.students[i].urls
              }
            }
            const Urls = this.getUrlsBySecondDir(name, result.fileDetails);
            console.log(Urls)
            const fileLimit = this.fileLimit;
            let finalUrls =resultUrls.concat(Urls);
            let emptyUrlCount = 0;
            if( fileLimit - Urls.length >=0){
              emptyUrlCount = fileLimit - Urls.length;
              for (let i = 0; i < emptyUrlCount; i++) {
                finalUrls.push("");
              }
            }
            let remark="";
            let fileTypes=[];
            for(let i=0;i<this.students.length;i++){
              if(item.id === this.students[i].id){
                remark =this.students[i].remark
                fileTypes= this.students[i].fileTypes;
              }
            }

            if( fileLimit - fileTypes.length >=0){
              const num = fileLimit - fileTypes.length;
              for (let i = 0; i < num; i++) {
                fileTypes.push("");
              }
            }

            return {
              id:item.id,
              name:name,
              registrationId:item.id,
              urls: finalUrls,
              remark:remark,
              fileTypes:fileTypes
              }
          })
          console.log(this.studentInitialData)
      }else{
        const targetStudents=result.targetStudents
          this.studentInitialData=targetStudents.map(item =>{
            let name =item.name
            let resultUrls =[]
            const Urls = this.getUrlsBySecondDir(name, result.fileDetails);
            const fileLimit = this.fileLimit;
            let finalUrls =resultUrls.concat(Urls);
            let emptyUrlCount = 0;
            if( fileLimit - Urls.length >=0){
              emptyUrlCount = fileLimit - Urls.length;
              for (let i = 0; i < emptyUrlCount; i++) {
                finalUrls.push("");
              }
            }
            let remark="";
            let fileTypes=[];

            if( fileLimit - fileTypes.length >=0){
              const num = fileLimit - fileTypes.length;
              for (let i = 0; i < num; i++) {
                fileTypes.push("");
              }
            }

            return {
              id:item.id,
              name:name,
              registrationId:item.id,
              urls: finalUrls,
              remark:remark,
              fileTypes:fileTypes
              }
          })
          console.log(this.studentInitialData)
      }

      // 关闭上传模态框
      this.showUploadModal = false;

      // 核心：更新学员档案数据（按姓名分组URL）
      this.updateStudentDataAfterUpload(result);

      // 显示确认页面
      this.showFileConfirmation = true;

      // 滚动到页面顶部
      window.scrollTo(0, 0);
    },


    /**
     * 处理FileUploadConfirmation的提交事件
     */
    handleFileSubmit(submitData) {
      console.log('档案信息提交，数据结构：', submitData);

      // 保存提交结果（调试用）
      this.submitResult = submitData;

      // 模拟API请求（实际项目替换为真实接口）
      handleRecordsSubmit(submitData).then((response) => {
        // 显示成功提示
        this.resultSuccess = true;
        this.resultMessage = "档案信息已成功保存至服务器";
        this.showResultDialog = true;

        // 关闭确认页面
        this.showFileConfirmation = false;
      });
    },
    handleMidwaySave(submitData) {
      console.log('中途保存数据（当前及之前用户）:', submitData);
      // 保存提交结果（调试用）
      this.submitResult = submitData;

      // 模拟API请求（实际项目替换为真实接口）
      handleRecordsSubmit(submitData).then((response) => {
        console.log(response.rows);
        // 显示成功提示
        this.resultSuccess = true;
        this.resultMessage = "档案信息已成功保存至服务器";
        this.showResultDialog = true;

        // 关闭确认页面
        this.showFileConfirmation = false;
      });
    },


    /**
     * 关闭所有模态框/组件
     */
    closeAllModals() {
      this.showUploadModal = false;
      this.showFileConfirmation = false;
    },


    /**
     * 处理上传模态框关闭事件
     */
    handleModalClose() {
      // console.log("上传模态框已手动关闭");
      this.showUploadModal = false;
    },


    /**
     * 核心方法：上传后更新学员档案数据（按姓名分组URL）
     * @param {Object} uploadResult - 上传结果数据（含fileDetails和relativePath）
     */
    updateStudentDataAfterUpload(uploadResult) {
      // 1. 校验上传结果有效性
      if (!uploadResult || !uploadResult.fileDetails || uploadResult.fileDetails.length === 0) {
        this.$message.warning("未获取到有效上传文件，学员档案未更新");
        return;
      }

      try {
        // 2. 按学员姓名分组URL（从relativePath提取姓名，新格式：test/学员姓名/文件名）
        const studentUrlMap = this.groupUrlsByStudentName(uploadResult.fileDetails);
        if (Object.keys(studentUrlMap).length === 0) {
          this.$message.warning("未从文件路径中提取到有效学员姓名，无法更新档案");
          return;
        }

        // 3. 根据分组结果更新对应学员的URLs
        this.updateStudentUrlsByGroup(studentUrlMap,uploadResult.uploadMode);

        // 4. 提示更新结果
        const updatedStudentCount = Object.keys(studentUrlMap).length;
        this.$message.success(`已成功更新${updatedStudentCount}名学员的档案，共新增${uploadResult.fileDetails.length}个文件`);

      } catch (error) {
        // console.error("更新学员档案时发生错误：", error);
        this.$message.error(`档案更新失败：${error.message || '未知错误'}`);
      }
    },


    /**
 * 辅助方法1：从fileDetails中按学员姓名分组URL（核心：解析relativePath）
 * @param {Array} fileDetails - 上传文件详情数组（含relativePath和url）
 * @returns {Object} 学员姓名→URL数组的映射（格式：{ "张三": [url1, url2] }）
 * @description 适配三层路径格式：任意前缀/学员姓名/文件名.后缀
 */
  groupUrlsByStudentName(fileDetails) {
    const studentUrlMap = {};

    fileDetails.forEach((file, index) => {
      // 1. 基础校验：文件详情必须包含relativePath和url
      if (!file.relativePath || !file.url) {
        // console.warn(`第${index + 1}个文件信息不完整（缺少路径或URL），跳过处理`);
        return;
      }

      // 2. 解析路径：按"/"分割，过滤空片段（处理前后斜杠导致的空值）
      const pathSegments = file.relativePath.split("/")
        .filter(segment => segment.trim() !== "");

      // 3. 格式校验：必须满足三层结构 "任意前缀/学员姓名/文件名" → 至少3个有效片段
      if (pathSegments.length < 3) {
        // console.warn(`第${index + 1}个文件路径格式错误（应为"任意前缀/学员姓名/文件名"）：${file.relativePath}，跳过处理`);
        return;
      }

      // 4. 提取学员姓名：第2个有效片段（索引1，三层结构中固定为学员姓名位置）
      const studentName = pathSegments[1].trim()
        .replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, ""); // 只保留中文、字母、数字

      // 5. 姓名有效性校验
      if (!studentName) {
        // console.warn(`第${index + 1}个文件路径中未提取到有效学员姓名：${file.relativePath}，跳过处理`);
        return;
      }

      // 6. 分组URL（去重，避免重复添加同一文件）
      if (!studentUrlMap[studentName]) {
        studentUrlMap[studentName] = [];
      }
      if (!studentUrlMap[studentName].includes(file.url)) {
        studentUrlMap[studentName].push(file.url);
        // console.log(`文件关联成功：学员「${studentName}」→ 文件名「${file.name}」→ URL「${file.url}」`);
      } else {
        // console.log(`文件已存在：学员「${studentName}」的「${file.name}」无需重复添加`);
      }
    });

    return studentUrlMap;
  },


    /**
     * 辅助方法2：根据姓名分组结果，更新studentInitialData对应学员的URLs
     * @param {Object} studentUrlMap - 学员姓名→URL数组的映射
     */
    updateStudentUrlsByGroup(studentUrlMap,uploadMode) {
      this.studentInitialData.forEach((student, studentIndex) => {
        // 找到当前学员在分组中的新URL列表
        const newUrls = studentUrlMap[student.name] || [];
        if (newUrls.length === 0) return; // 无对应新URL，跳过当前学员

        // 1. 保留学员原有非空URL（避免覆盖已存在的有效档案）
        const existingValidUrls = student.urls.filter(url => url && url.trim() !== "");
        console.log(`学员「${student.name}」原有有效档案数：${existingValidUrls.length}个`);

        // 2. 合并原有URL和新URL（去重处理）
        const mergedUrls = [...new Set([...existingValidUrls, ...newUrls])];
        console.log(`学员「${student.name}」合并后总档案数：${mergedUrls.length}个`);

        // 3. 按规则限制文件数量
        const fileLimit = this.fileLimit; // 所有学员最多6个文件
        const finalUrls = mergedUrls.slice(0, fileLimit); // 超过限制时截取前N个

        // 4. 补充空URL至限制数量（保持界面显示一致，空URL对应"点击上传"提示）
        const emptyUrlCount = fileLimit - finalUrls.length;
        for (let i = 0; i < emptyUrlCount; i++) {
          finalUrls.push("");
        }

        // 5. 响应式更新学员URLs（必须用$set确保Vue检测到数组变化）
        this.$set(student, "urls", finalUrls);
        // console.log(uploadMode)
        // if(uploadMode === "1"){
        //   console.log(student.urls)
        //   const mergedUrls = [...new Set([...student.urls, ...newUrls])];student.urls
        //   console.log(mergedUrls)
        //   this.$set(student, "urls", mergedUrls);
        // }else{
        //   console.log(newUrls)
        //   this.$set(student, "urls", newUrls);
        // }

        // 6. 日志提示最终结果
        const addedCount = mergedUrls.length - existingValidUrls.length;
        // console.log(
        //   `学员「${student.name}」档案更新完成：新增${addedCount}个，当前共${finalUrls.filter(url => url).length}个有效档案（限制${fileLimit}个）`
        // );
      });
    },

    /**
     * 刷新学员数据（从后端获取最新数据，实际项目使用）
     */
    refreshStudentData() {
      this.$message.info('正在从服务器刷新最新档案数据...');

      // 模拟API请求（实际项目替换为真实接口）
      setTimeout(() => {
        // 响应式更新学员初始数据
        // this.studentInitialData = mockNewData;
        this.$message.success('档案数据已刷新，与服务器保持同步');
      }, 1000);
    },
    async handleExportTest1() {
      console.log(this.recordDto)
      this.registrationIdsUpload = this.registrationIds.join(',');
      if(this.ids.length !=0 ){
        this.registrationId =this.recordDto[0].registrationId
      }
      const response = await selectRecordsByRegistrationIds(this.registrationIdsUpload);
      this.students=response.map(item =>{
          const recordsList=item.recordsList
          let fileTypes=[]
          let urls=[]
          for(let i=0;i<recordsList.length;i++){
            fileTypes.push(recordsList[i].recordType)
            urls.push(recordsList[i].url)
          }
          return {
            id:item.registrationId,
            name:item.studentName,
            requirements: ["身份证", "报名表"],
            remark:item.remark,
            fileTypes:fileTypes,
            urls:urls
          }
        })
      this.showUploadModal=true
    },
    async handleExportTest2() {
      this.registrationIdsUpload = this.registrationIds.join(',');
      if(this.ids.length !=0 ){
        this.registrationId =this.recordDto[0].registrationId
      }
      const response=await selectRecordsByRegistrationIds(this.registrationIdsUpload)
      this.students=response.map(item =>{
          const recordsList=item.recordsList
          let fileTypes=[]
          let urls=[]
          for(let i=0;i<recordsList.length;i++){
            fileTypes.push(recordsList[i].recordType)
            urls.push(recordsList[i].url)
          }

          //补充
          let resultUrls =[]
          let resultFileTypes =[]
          const fileLimit = this.fileLimit;
            let finalUrls =resultUrls.concat(urls);
            let emptyUrlCount = 0;
            if( fileLimit - urls.length >=0){
              emptyUrlCount = fileLimit - urls.length;
              for (let i = 0; i < emptyUrlCount; i++) {
                finalUrls.push("");
              }
            }
            let fileTypesFinal=resultFileTypes.concat(fileTypes);

            if( fileLimit - fileTypes.length >=0){
              const num = fileLimit - fileTypes.length;
              for (let i = 0; i < num; i++) {
                fileTypesFinal.push("");
              }
            }
          return {
            id:item.registrationId,
            name:item.studentName,
            requirements: ["身份证", "报名表"],
            remark:item.remark,
            fileTypes:fileTypesFinal,
            urls:finalUrls
          }
        })
        this.studentInitialData=this.students.map(item =>{
            return {
              id:item.id,
              name:item.name,
              registrationId:item.id,
              urls: item.urls,
              remark:item.remark,
              fileTypes:item.fileTypes
              }
          })
      this.showFileConfirmation=true
    },
  }
};
</script>
<style scoped>
.el-form-item--mini .el-form-item__label {
  padding: 0 0 0 10px;
}
.el-button--primary {
  background-color: #007aff;
  border-color: #007aff;
}
.group-label {
  color: #666;
  font-weight: 500;
  white-space: nowrap;
  font-size: 16px;
  margin: auto;
  margin-right: 5px;
  width: 100px; /* 固定宽度 */
  text-align: right; /* 右对齐 */
  display: inline-block;
  vertical-align: middle;
}

.el-button {
  width: 100px;
  height: 32px;
  line-height: 32px;
  padding: 0;
  text-align: center;
  font-size: 14px;
  margin-right: 8px;
}
</style>


